import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  ScrollView,
  TouchableOpacity,
  Keyboard,
  Modal,
  TouchableWithoutFeedback,
  KeyboardAvoidingView,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {LinearButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import DatePicker from 'react-native-date-picker';
import LayoutConstants from '../../config/LayoutConstants';
import {LinerBoardTextInput} from '../../components/TextInput';
import LinearGradient from 'react-native-linear-gradient';
import {Picker} from '@react-native-picker/picker';

class AuctionSet extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      payCoin: {
        symbol: 'BNB',
        contractAddress: '0x0000000000000000000000000000000000000000',
      },
      selPayCoin: 'BNB',
      price: '',
      date: '',
      selDate: '',
      maxPrice: '',
      minIncreasePrice: '',
      modalVisible: false,
      showDatePicker: true,
    };

    if (props.coins.length != 0) {
      this.state.payCoin = props.coins[0];
    }
  }

  renderComponent = () => {
    let {modalVisible, date, payCoin, maxPrice, price, selPayCoin} = this.state;

    let minDate = new Date(
      new Date().valueOf() + 7 * 24 * 60 * 60 * 1000 + 10 * 60 * 1000,
    );
    let maxDate = new Date(new Date().valueOf() + 30 * 24 * 60 * 60 * 1000);

    let top =
      500 +
      Math.sqrt(
        Math.pow(500, 2) - Math.pow(LayoutConstants.WINDOW_WIDTH / 2, 2),
      );
    let {img, name} = this.props.navigation.state.params.nft;
    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text=""
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />

        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{width: '100%', flex: 1}}>
          <ScrollView keyboardDismissMode={true} style={{flex: 1}}>
            <View
              style={{
                width: 1000,
                height: 1000,
                alignSelf: 'center',
                marginTop: -top,
                borderRadius: 500,
                backgroundColor: '#160231',
              }}></View>
            <Image
              style={{
                width: 90,
                height: 90,
                borderRadius: 10,
                alignSelf: 'center',
                marginTop: -30,
              }}
              source={{uri: img}}></Image>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#8A7B6C',
                alignSelf: 'center',
                marginTop: 10,
              }}>
              {name}
            </Text>
            <View style={{paddingLeft: 20, paddingRight: 20}}>
              <View
                style={{
                  height: 30,
                  borderRadius: 20,
                  backgroundColor: '#571DAA',
                  position: 'relative',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginTop: 20,
                }}>
                <Text style={{fontWeight: 'bold', color: 'white'}}>
                  Auction Set
                </Text>
                <Image
                  style={{position: 'absolute', right: 20, top: -10}}
                  source={require('../../assets/auction/auction.png')}></Image>
              </View>
              <Text
                style={{
                  fontWeight: 'bold',
                  fontSize: 18,
                  color: '#7505F4',
                  marginTop: 20,
                }}>
                Auction Pay Coin
              </Text>
              <Text
                style={{
                  color: '#4A4A4A',
                  marginBottom: 10,
                  fontSize: 14,
                  marginTop: 10,
                }}>
                Select a token you want to use to pay for the auction.
              </Text>
              <TouchableOpacity
                style={{
                  width: '100%',
                  justifyContent: 'center',
                }}
                onPress={() => {
                  this.setState({
                    modalVisible: true,
                    showDatePicker: false,
                  });
                }}>
                <LinearGradient
                  start={{x: 0, y: 1}}
                  end={{x: 1, y: 1}}
                  colors={['#CE18EC', '#6601F5']}
                  style={{
                    height: 44,
                    borderRadius: 22,
                    padding: 2,
                    shadowColor: 'rgba(255,105,201,0.50)',
                    shadowOffset: {width: 2, height: 4},
                    shadowOpacity: 0.8,
                    flexDirection: 'row',
                  }}>
                  <View
                    style={{
                      borderRadius: 20,
                      backgroundColor: 'white',
                      position: 'relative',
                      flex: 1,
                      justifyContent: 'center',
                      // alignItems: 'center',
                      paddingLeft: 20,
                      paddingRight: 20,
                    }}>
                    <Text style={{color: 'black'}}>{payCoin.symbol}</Text>
                  </View>
                </LinearGradient>
              </TouchableOpacity>
              <Text
                style={{
                  fontWeight: 'bold',
                  fontSize: 18,
                  color: '#7505F4',
                  marginTop: 20,
                }}>
                Minimum Bid
              </Text>
              <Text
                style={{
                  color: '#4A4A4A',
                  marginBottom: 10,
                  fontSize: 14,
                  marginTop: 10,
                }}>
                Set your starting bid price.if you receive a bid above this
                starting value. you can accept it any time.
              </Text>
              <LinerBoardTextInput
                placeholder={'0.0'}
                suffix={payCoin.symbol}
                keyboardType={'numeric'}
                onChangeText={(text) => {
                  this.setState({
                    price: text,
                  });
                }}
              />
              <Text
                style={{
                  fontWeight: 'bold',
                  fontSize: 18,
                  color: '#7505F4',
                  marginTop: 20,
                }}>
                Maximum Bid
              </Text>
              <Text
                style={{
                  color: '#4A4A4A',
                  marginBottom: 10,
                  fontSize: 14,
                  marginTop: 10,
                }}>
                Set a maximum price. When the price reaches or exceeds this
                price, your auction will close immediately
              </Text>
              <LinerBoardTextInput
                placeholder={'0.0'}
                suffix={payCoin.symbol}
                keyboardType={'numeric'}
                onChangeText={(text) => {
                  this.setState({
                    maxPrice: text,
                  });
                }}
              />
              <View>
                <Text
                  style={{
                    fontWeight: 'bold',
                    fontSize: 18,
                    color: '#7505F4',
                    marginTop: 20,
                  }}>
                  Minimum Increase Price
                </Text>
                <Text
                  style={{
                    color: '#4A4A4A',
                    marginBottom: 10,
                    fontSize: 14,
                    marginTop: 10,
                  }}>
                  The minimum amount of increase price.
                </Text>
                <LinerBoardTextInput
                  placeholder={'0.0'}
                  suffix={payCoin.symbol}
                  keyboardType={'numeric'}
                  onChangeText={(text) => {
                    this.setState({
                      minIncreasePrice: text,
                    });
                  }}
                />
              </View>
              <Text
                style={{
                  fontWeight: 'bold',
                  fontSize: 18,
                  color: '#7505F4',
                  marginTop: 10,
                }}>
                Expiration Date
              </Text>
              <Text
                style={{
                  color: '#4A4A4A',
                  marginBottom: 10,
                  fontSize: 14,
                  marginTop: 10,
                }}>
                Your auction will automatically end at this time and the highest
                bidder will win.
              </Text>
              <TouchableOpacity
                style={{
                  width: '100%',
                  justifyContent: 'center',
                }}
                onPress={() => {
                  this.setState({
                    selDate: new Date(),
                    modalVisible: true,
                    showDatePicker: true,
                  });
                }}>
                <LinearGradient
                  start={{x: 0, y: 1}}
                  end={{x: 1, y: 1}}
                  colors={['#CE18EC', '#6601F5']}
                  style={{
                    height: 44,
                    borderRadius: 22,
                    padding: 2,
                    shadowColor: 'rgba(255,105,201,0.50)',
                    shadowOffset: {width: 2, height: 4},
                    shadowOpacity: 0.8,
                    flexDirection: 'row',
                  }}>
                  <View
                    style={{
                      borderRadius: 20,
                      backgroundColor: 'white',
                      position: 'relative',
                      flex: 1,
                      justifyContent: 'center',
                      // alignItems: 'center',
                      paddingLeft: 20,
                      paddingRight: 20,
                    }}>
                    <Text
                      style={{color: date.length == 0 ? '#A1A1A1' : 'black'}}>
                      {date.length == 0
                        ? 'Select the auction deadline'
                        : date.toString()}
                    </Text>
                  </View>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
        <LinearButton
          buttonStyle={{alignSelf: 'center', width: 180, marginBottom: 50}}
          text={'Next'}
          onPress={() => {
            console.log(this.state.date);
            console.log(this.state.price);
            console.log(this.state.minIncreasePrice);
            console.log(this.state.maxPrice);

            if (Number(this.state.price) < 0) {
              this._showAlert({content: 'Please input minimum bid'});
              return;
            }
            if (Number(this.state.maxPrice) <= 0) {
              this._showAlert({content: 'Please input maximum bid.'});
              return;
            }
            if (Number(this.state.minIncreasePrice) <= 0) {
              this._showAlert({content: 'Please input minIncrease price.'});
              return;
            }
            if (this.state.date.length <= 0) {
              this._showAlert({content: 'Please select expiration date.'});
              return;
            }
            if (Number(this.state.maxPrice) < Number(this.state.price)) {
              this._showAlert({
                content: 'maximum bid must be bigger than minimum bid.',
              });
              return;
            }

            let newNft = {
              ...this.props.navigation.state.params.nft,
              price: this.state.price,
              maxPrice: this.state.maxPrice,
              payCoin: this.state.payCoin,
              date: this.state.date,
              minIncreasePrice: this.state.minIncreasePrice,
            };
            this.props.navigation.navigate('Summary', {nft: newNft});
          }}
        />
        <Modal animationType="fade" transparent visible={modalVisible}>
          <View
            style={{
              justifyContent: 'flex-end',
              flex: 1,
              backgroundColor: 'rgba(33,33,33,0.4)',
            }}>
            <TouchableWithoutFeedback
              onPress={() => {
                if (this.state.selDate.length == 0) {
                  this.setState({
                    selDate: minDate,
                  });
                }
                this.setState({
                  modalVisible: false,
                });
              }}>
              <View
                style={{
                  flex: 1,
                  width: '100%',
                }}></View>
            </TouchableWithoutFeedback>
            <View
              style={{
                backgroundColor: 'white',
                width: '100%',
                alignItems: 'center',
              }}>
              {this.state.showDatePicker ? (
                <DatePicker
                  androidVariant="iosClone"
                  minimumDate={minDate}
                  maximumDate={maxDate}
                  date={this.state.selDate}
                  onDateChange={(date) => {
                    this.setState({
                      selDate: date,
                    });
                  }}
                  mode="datetime"></DatePicker>
              ) : (
                <Picker
                  mode="dropdown"
                  numberOfLines={5}
                  style={{height: 200, width: '80%'}}
                  selectedValue={selPayCoin}
                  onValueChange={(itemValue, itemIndex) => {
                    console.log('选择的itemValue');
                    console.log(itemValue);
                    this.setState({
                      selPayCoin: itemValue,
                    });
                  }}>
                  {this.props.coins.map((item, idx) => {
                    return (
                      <Picker.Item
                        label={item.symbol}
                        value={item.symbol}
                        key={'coins-opt' + idx}
                      />
                    );
                  })}
                </Picker>
              )}
              <LinearButton
                buttonStyle={{width: 150, marginBottom: 20}}
                onPress={() => {
                  // console.log(this.state.selDate);

                  if (this.state.showDatePicker) {
                    this.setState({
                      date:
                        this.state.selDate.valueOf() < minDate.valueOf()
                          ? minDate
                          : this.state.selDate,
                      modalVisible: false,
                    });
                  } else {
                    this.setState({
                      payCoin: this.props.coins.filter(
                        (item) => item.symbol === selPayCoin,
                      )[0],
                      modalVisible: false,
                    });
                  }
                }}
                text={'Sure'}
              />
            </View>
          </View>
        </Modal>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  gasSymbol: state.Chain.gasSymbol,
  swapSymbol: state.Chain.swapSymbol,
  coins: state.Chain.coins,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(AuctionSet);
